#pragma once

#include "ChannelManager.hpp"
#include <memory>

namespace micromq
{
    class Connection
    {
    public:
        using ptr = std::shared_ptr<Connection>;
    public:
        Connection(const VirtualHost::ptr& host, const ConsumerManager::ptr& consumerManager, 
            const muduo::net::TcpConnectionPtr& conn, const ProtobufCodecPtr& codec)
            : _channelManager(std::make_shared<ChannelManager>()),  _host(host), _consumerManager(consumerManager)
            , _conn(conn), _codec(codec)
        {}

        void openChannel(const OpenChannelRequestPtr& req)
        {
            bool result = _channelManager->openChannel(req->channel_id(), _host, _consumerManager, _conn, _codec);
            sendCommonResponse(req->req_id(), req->channel_id(), result);
        }

        void closeChannel(const CloseChannelRequestPtr& req)
        {
            _channelManager->closeChannel(req->req_id());
            sendCommonResponse(req->req_id(), req->channel_id(), true);
        }

        Channel::ptr getChannelById(const std::string& channelId)
        {
            return _channelManager->getChannel(channelId);
        }

        ~Connection()
        {}
    private:
        void sendCommonResponse(const std::string& reqId, const std::string& channelId, bool isOk)
        {
            CommonResponse resp;
            resp.set_resp_id(reqId);
            resp.set_channel_id(channelId);
            resp.set_is_ok(isOk);
            _codec->send(_conn, resp);
        }
    private:
        VirtualHost::ptr _host;
        ChannelManager::ptr _channelManager;
        ConsumerManager::ptr _consumerManager;
        
        muduo::net::TcpConnectionPtr _conn;
        ProtobufCodecPtr _codec;
    };
}